package com.zcyppyh.ddns.service;

import cn.hutool.cron.CronUtil;
import cn.hutool.cron.task.Task;
import com.zcyppyh.ddns.config.ConfigFile;
import com.zcyppyh.ddns.utils.ProjectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Component
@Order(value = 10)
public class CronStart implements CommandLineRunner {
    private static final Logger logger = LoggerFactory.getLogger(CronStart.class);

    @Value("${config.cron}")
    private String cron;

    @Resource
    private ConfigFile configFile;

    @Override
    public void run(String... args) throws Exception {
        logger.info("开始启动定时任务。。。。。。");
        List<String> crons = ProjectUtil.getProjectConfig().getCronList();
        if(crons.isEmpty()){
            crons = new ArrayList<>(Arrays.asList(cron));
        }
        //启动定时任务
        for (int i = 0; i<crons.size(); i++) {
            String c = crons.get(i);
            logger.info("定时任务[{}]规则如下:[{}]", i, c);
            CronUtil.schedule(c, new Task() {
                @Override
                public void execute() {
                    Dns dns = new Dns();
                    try {
                        dns.execute();
                    } catch (Exception e) {
                        //*****
                    }
                }
            });
        }
        CronUtil.start();
        logger.info("定时任务成功启动。。。。。。");
    }
}
